import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe, Logger } from '@nestjs/common';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
import { setupSwagger } from './swagger.config';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const logger = new Logger('Main');
  
  // 全局异常过滤器
  app.useGlobalFilters(new HttpExceptionFilter());
  
  // 全局请求日志中间件
  app.use((req, res, next) => {
    logger.log(`收到请求: ${req.method} ${req.url}`);
    logger.log(`请求头: ${JSON.stringify(req.headers)}`);
    if (req.body) {
      logger.log(`请求体: ${JSON.stringify(req.body)}`);
    }
    next();
  });
  
  // 全局验证管道
  app.useGlobalPipes(new ValidationPipe({
    whitelist: true,        // 只保留DTO中定义的字段
    forbidNonWhitelisted: false,  // 不禁止未定义的字段，直接忽略
    transform: true,        // 自动转换类型
    skipMissingProperties: false, // 不跳过缺失的属性
    skipNullProperties: false,    // 不跳过null值
    skipUndefinedProperties: false, // 不跳过undefined值
    exceptionFactory: (errors) => {
      const messages = errors.map(error => 
        Object.values(error.constraints || {}).join(', ')
      );
      return new Error(messages.join('; '));
    }
  }));

  // CORS配置
  app.enableCors();

  // 全局前缀
  app.setGlobalPrefix('api');

  // 设置Swagger文档
  setupSwagger(app);

  const port = process.env.PORT || 3000;
  await app.listen(port);
  logger.log(`🚀 应用已启动，监听端口: ${port}`);
  logger.log(`📖 API文档地址: http://localhost:${port}/api`);
  logger.log(`📚 Swagger文档: http://localhost:${port}/api-docs`);
}
bootstrap();
